<template>
  <el-drawer
    size="720px"
    title="选择扫描范围"
    append-to-body
    custom-class="scope-range-drawer"
    :modelValue="props.modelValue"
    @update:model-value="(v) => emit('update:model-value', v)"
  >
    <el-form @submit.prevent ref="formRef" label-width="100px" :model="formOption">
      <el-row>
        <el-col :span="12" v-if="type === 3">
          <el-form-item :label="'表名称'" prop="table">
            <ns-input :placeholder="'请输入表名称'" v-model="formOption.table" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="type !== 1">
          <el-form-item :label="'schema名称'" prop="schema">
            <ns-input
              :placeholder="'请输入schema名称'"
              v-model="formOption.schema"
              clearable
            /> </el-form-item
        ></el-col>
        <el-col :span="12">
          <el-form-item label="库名称" prop="db">
            <ns-input placeholder="请输入库名称" v-model="formOption.db" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="type !== 2 ? 12 : 24" class="text-right">
          <el-button type="primary" @click="query">搜索</el-button>
          <el-button @click="resetSearch"> 重置 </el-button>
        </el-col>
      </el-row>
    </el-form>
    <el-divider />
    <div>
      <h3 class="m-section-title inline-block">
        <span class="m-section-title__text">{{ labelList[type] }}列表</span>
      </h3>
      <el-button
        :loading="scaning"
        type="primary"
        class="float-right"
        @click="handleScan"
        :disabled="!isScan"
        >{{ scaning ? `${process}` : '扫描数据' }}</el-button
      >
    </div>
    <AsyncTable
      v-loading="loading"
      ref="tableRef"
      :columns="columns"
      :fetchData="fetchData"
      @selection-change="handleSelectionChange"
      :checkBackSelect="checkBackList"
    />
    <div class="float-right mt-16px">
      <el-button type="primary" @click="submit">确 定</el-button>
      <el-button @click="() => emit('update:model-value', false)">取 消</el-button>
    </div>
  </el-drawer>
</template>

<script setup>
import { getMetaInfoPage, scanData, scanDataProgress } from '@/api/asset/taskManage/dataCollect'
import { cloneDeep } from 'lodash-es'
import { SM4Encrypt } from '@/utils/sm4Util'
const emit = defineEmits(['update', 'update:model-value'])
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  type: {
    type: Number,
    default: 1
  },
  connection: {
    type: Object,
    default: () => {}
  },
  selectInfo: {
    type: Array,
    default: () => []
  },
  isScan: {
    type: Boolean,
    default: false
  },
  deviceId: {
    type: String,
    default: ''
  },
  filterSys: {
    type: String,
    default: '0'
  }
})
const connectionInfo = {
  authType: '',
  appType: '',
  isDefault: 0,
  connectType: '',
  intactInfo: '',
  params: {}
}
const formOption = reactive({
  db: '',
  schema: '',
  table: ''
})
const labelList = reactive({
  1: '库',
  3: '表',
  2: 'schema'
})
const dataTypeList = reactive({
  1: 'db',
  3: 'table',
  2: 'schema'
})
const checkBackList = ref([])
const scaning = ref(false)
const timer = ref(null)
const process = ref('0%')
const currentCount = ref(-1)
const columns = ref([])
const baseColumns = [
  [
    { type: 'selection', width: 42, 'reserve-selection': true },
    {
      label: '库名称',
      prop: 'name',
      'min-width': 100,
      'show-overflow-tooltip': true
    }
  ],
  [
    { type: 'selection', width: 42, 'reserve-selection': true },
    {
      label: 'schema名称',
      prop: 'name',
      'min-width': 100,
      'show-overflow-tooltip': true
    },
    { label: '所属库', prop: 'db', 'min-width': 100, 'show-overflow-tooltip': true }
  ],
  [
    { type: 'selection', width: 42, 'reserve-selection': true },
    {
      label: '表名称',
      prop: 'name',
      'min-width': 100,
      'show-overflow-tooltip': true
    },
    { label: '所属schema', prop: 'schema', 'min-width': 100, 'show-overflow-tooltip': true },
    { label: '所属库', prop: 'db', 'min-width': 100, 'show-overflow-tooltip': true }
  ]
]
const tableRef = ref()
const formRef = ref()
const loading = ref(false)
const selectedRows = ref([])

function cancel() {
  emit('update:model-value', false)
}

function submit() {
  emit('update', selectedRows.value)
  emit('update:model-value', false)
}

function handleSelectionChange(rows) {
  selectedRows.value = rows.map((item) => {
    return item.metaInfoName
  })
}

async function fetchData({ page, pageSize }) {
  loading.value = true
  let data = {
    ...formOption,
    connection: { ...connectionInfo, deviceId: props.deviceId },
    dataType: dataTypeList[props.type],
    pageSize: pageSize,
    page: page
  }
  const res = await getMetaInfoPage(data)
  loading.value = false
  return {
    data: res.data,
    count: res.count
  }
}
function query() {
  tableRef.value.resetPage()
  tableRef.value.fetchData()
}
function resetSearch() {
  formRef.value.resetFields()
  query()
}
function handleScan() {
  process.value = '0%'
  scaning.value = true
  scanData({
    dataType: dataTypeList[props.type],
    connectionProperties: { ...connectionInfo, deviceId: props.deviceId },
    filterSys: props.filterSys
  }).then((res) => {})
  if (timer.value) clearTimeout(timer.value)
  timer.value = setTimeout(() => {
    getScanProcess()
  }, 1500)
}

async function getScanProcess() {
  const data = await scanDataProgress({
    dataType: dataTypeList[props.type],
    connectionProperties: { ...connectionInfo, deviceId: props.deviceId }
  })
  if (data?.progress === 100) {
    process.value = '获取数据中'
    const { count } = await fetchData({ page: 1, pageSize: 10 })
    currentCount.value = count
  } else {
    process.value = data?.progress + '%'
  }
  if (currentCount.value === data?.msgCount) {
    scaning.value = false
    query()
    currentCount.value = -1
  } else {
    if (timer.value) clearTimeout(timer.value)
    timer.value = setTimeout(() => {
      getScanProcess()
    }, 3000)
  }
}

onMounted(() => {
  checkBackList.value = props.selectInfo.map((item) => {
    return { metaInfoName: item }
  })
  columns.value = baseColumns[props.type - 1]
  for (let item in props.connection) {
    if (connectionInfo[item] != undefined) {
      if (typeof connectionInfo[item] == 'object') {
        connectionInfo[item] = cloneDeep(props.connection[item])
      } else {
        connectionInfo[item] = props.connection[item]
      }
    }
  }
  for (const k in connectionInfo.params) {
    if (
      k.indexOf('password') > -1 ||
      k.indexOf('Password') > -1 ||
      k.indexOf('dbAccount') > -1 ||
      k.indexOf('userName') > -1
    )
      connectionInfo.params[k] && (connectionInfo.params[k] = SM4Encrypt(connectionInfo.params[k]))
  }
})
onBeforeUnmount(() => {
  if (timer.value) clearTimeout(timer.value)
})
</script>
<style lang="scss">
.scope-range-drawer {
  .el-drawer__header {
    margin-bottom: 10px;
  }
  &.el-drawer .el-drawer__body {
    padding: 20px !important;
  }
  .m-section-title {
    margin-bottom: 10px;
    margin-top: 0px;
    height: 24px;
    line-height: 24px;
    font-size: 16px;

    &::before {
      content: ' ';
      display: inline-block;
      width: 4px !important;
      height: 16px;
      background-color: var(--el-color-primary);
      margin-right: 10px;
      position: relative;
      top: 3px;
    }

    .m-section-title__text {
      font-weight: 500;
      font-family: PingFangSC-Medium;
    }
  }
}
</style>
